import UIKit

class PhotoMessageViewModel: PhotoRepresentableMessageViewModel, AttachmentLoadingViewModel {
    
    var progress: Double?
    
    var progressObject: ChatProgressBridge? {
        didSet {
            progressObject?.updateProgress = { [weak self] (progress: Float) -> Void in
                guard let `self` = self else { return }
                DispatchQueue.main.async {
                    self.progress = Double(progress)
                    self.updateProgress?(self)
                }
            }
        }
    }

    var automaticallyLoadsAttachment: Bool {
        return mediaStatus == MediaStatus.PENDING.rawValue && !messageIsSentByMe
    }
    
    var showPlayIconAfterFinished: Bool {
        return false
    }
    
    override init(message: MessageItem, style: Style, fits layoutWidth: CGFloat) {
        super.init(message: message, style: style, fits: layoutWidth)
        updateOperationButtonStyle()
    }
    
    func beginAttachmentLoading() {
        guard message.mediaStatus == MediaStatus.PENDING.rawValue || message.mediaStatus == MediaStatus.CANCELED.rawValue else {
            return
        }
        
        if message.isOutgoing == false, let model = message.model {
            ToxManager.shared.toxMananger!.files.acceptFileTransfer(model, failureBlock: { _ in
            })
        }
    }
    
    func cancelAttachmentLoading(markMediaStatusCancelled: Bool) {
        if let model = message.model {
            try? ToxManager.shared.toxMananger!.files.cancelFileTransfer(model)
        }
    }
    
    var updateProgress: ((AttachmentLoadingViewModel) -> Void)?
    
    func observeProgress(updateProgress: @escaping (AttachmentLoadingViewModel) -> Void) {
        guard let model = message.model, self.updateProgress == nil else { return }
        let progressBridge = ChatProgressBridge()
        _ = try? ToxManager.shared.toxMananger!.files.add(progressBridge, forFileTransfer: model)
        self.progressObject = progressBridge
        self.updateProgress = updateProgress
    }
}

/**
 Bridge between objcTox subscriber and chat progress protocol.
 */
class ChatProgressBridge: NSObject {
    var updateProgress: ((_ progress: Float) -> Void)?
    var updateEta: ((_ eta: CFTimeInterval, _ bytesPerSecond: OCTToxFileSize) -> Void)?
}

extension ChatProgressBridge: OCTSubmanagerFilesProgressSubscriber {
    func submanagerFiles(onProgressUpdate progress: Float, message: OCTMessageAbstract) {
        updateProgress?(progress)
    }
    
    func submanagerFiles(onEtaUpdate eta: CFTimeInterval, bytesPerSecond: OCTToxFileSize, message: OCTMessageAbstract) {
        updateEta?(eta, bytesPerSecond)
    }
}
